package com.eoner.baselib.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.R;
import com.eoner.baselib.enums.FCPageViewState;
import com.eoner.baselib.presenter.FCBasePresenter;
import com.eoner.baselib.presenter.IFCBaseView;
import com.eoner.baselib.utils.activity.ActivityHook;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.other.TUtil;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.empty.FCPageStateClickListener;
import com.eoner.baselib.widget.empty.FCPageStateView;
import com.eoner.baselib.widget.loading.FCPageLoading;
import com.eoner.baselib.widget.navgation.FCNavigationAction;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselib.widget.navgation.IFCNavigationListener;
import com.gyf.barlibrary.ImmersionBar;
import com.kaopiz.kprogresshud.KProgressHUD;
import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;

import butterknife.ButterKnife;

/**
 * 文件名：FCBaseActivity
 * 描 述：页面父类
 * 作 者：gyq
 * 时 间：2021-1-22
 */
public abstract class FCBaseActivity<T extends FCBasePresenter> extends AppCompatActivity implements IFCBaseView, FCPageStateClickListener {

    //是否在前台
    protected boolean isActive = true;
    //泛型 presenter
    protected T mPresenter;
    //上下文
    protected Context mContext;
    //基类(Activity)所使用的TAG标签
    protected String TAG = null;
    //通用字体
    protected Typeface mIconFont;
    //主视图
    protected ViewGroup mRootView;
    //内容试图
    protected FrameLayout mContainerView;
    //导航栏
    protected FCNavigationBar mNavigationBar;
    //pageLoading
    private FCPageLoading mPageLoading;
    //commitLoading
    private KProgressHUD mCommitLoading;
    //默认页面
    private FCPageStateView mStateView;
    //下拉刷新控件
    private SwipeRefreshLayout mRefreshView;

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      初始化
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //hook，绕过旋转方向检查
        ActivityHook.hookOrientation(this);
        super.onCreate(savedInstanceState);
        //初始化任务
        initTasks();
        //初始化view
        initViews();
        //初始化导航栏
        initNavigationBar();
        //初始化ui和数据
        requireInitUIAndData(savedInstanceState);
    }

    /**
    * 初始化任务
    * */
    protected void initTasks() {
        TAG = getClass().getSimpleName();
        mContext = this;
        // 将其子activity添加到activity采集器
        UtilActivity.addActivity(this);
        //获取公用字体
        mIconFont = Typeface.createFromAsset(getAssets(), "fonts/iconfont.ttf");
        //绑定路由
        ARouter.getInstance().inject(this);
        //绑定eventBus
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
        //初始化presenter(如果子类不是FCFragmentHostActivity)
        if (!(this instanceof FCFragmentHostActivity)){
            mPresenter = TUtil.getT(this,0);
            if (mPresenter != null) {
                mPresenter.setIView(this);
            }
        }
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    /**
    * 初始化view
    * */
    private void initViews() {
        setFullScreenAndTransparent(this);
        setAndroidNativeLightStatusBar(true);
        StatusBarUtil.setStatusBarColor(this, Color.parseColor("#FFFFFF"));
        if (useRefreshLayout()) {
            setContentView(R.layout.activity_base_refresh_gzg);
            mRefreshView = findViewById(R.id.sl_base_refresh);
        } else {
            setContentView(R.layout.activity_base_gzg);
        }

        //主视图
        mRootView = findViewById(R.id.ll_base_root);
        int layoutId = requireGetLayoutId();
        View contentView = getLayoutInflater().inflate(layoutId, null);
        mContainerView = findViewById(R.id.fl_base_container);
        mContainerView.addView(contentView);
        //ButterKnife绑定
        ButterKnife.bind(this,contentView);
    }

    /**
    * 初始化导航栏
    * */
    private void initNavigationBar() {
        mNavigationBar = findViewById(R.id.v_base_nav_bar);
        mNavigationBar.setGzgNavigationListener(new IFCNavigationListener() {
            @Override
            public void onNavigationClickListen(int action) {
                switch (action) {
                    case FCNavigationAction.NAV_LEFT_CLICK: {
                        onNavigationLeftClick();
                    }
                        break;
                    case FCNavigationAction.NAV_RIGHT_CLICK: {
                        onNavigationRightClick();
                    }
                        break;
                }
            }
        });
        if (isFullscreen()) {
            mNavigationBar.setVisibility(View.GONE);
        }
        requireSetCustomNavigationBar(mNavigationBar);
    }

    /**
     * 导航栏事件
     * */
    protected void onNavigationLeftClick() {
        finish();
    }

    protected void onNavigationRightClick() {
    }


    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      必须子类实现方法
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 获取布局
     * */
    protected abstract int requireGetLayoutId();

    /**
     * 自定义导航栏
     * */
    protected abstract void requireSetCustomNavigationBar(FCNavigationBar navigationBar);

    /**
     * 初始化UI和数据
     * */
    protected abstract void requireInitUIAndData(Bundle savedInstanceState);

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      控制方法
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 是否使用eventBus
     * */
    protected boolean useEventBus() {
        return false;
    }

    /**
     * 是否全屏幕
     * */
    protected boolean isFullscreen() {
        return false;
    }

    /**
     * 是否使用下拉刷新页面
     * */
    protected boolean useRefreshLayout() {
        return false;
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      IFCBaseView
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
    * 获取上下文
    * */
    @Override
    public Context context() {
        return this;
    }

    /**
     * 显示页面指示器
     * */
    @Override
    public void baseShowPageLoading(boolean isCanTouchOutSide) {
        if (mPageLoading == null) {
            mPageLoading = new FCPageLoading(this);
            mContainerView.addView(mPageLoading);
        }
        if (isCanTouchOutSide) {
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER;
            mPageLoading.setLayoutParams(layoutParams);
        } else {
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);
            mPageLoading.setLayoutParams(layoutParams);
        }
        mPageLoading.showProgressLoading();
    }

    /**
     * 隐藏页面指示器
     * */
    @Override
    public void baseHiddenPageLoading() {
        if (mPageLoading != null) {
            mPageLoading.hiddenLoading();
        }
    }

    /**
     * 显示提交指示器
     * */
    @Override
    public void baseShowCommitLoading(String msg) {
        if (mCommitLoading == null) {
            mCommitLoading = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
//            mCommitLoading.setSize(114,92);
            mCommitLoading.setBackgroundColor(Color.parseColor("#80000000"));
            mCommitLoading.setCancellable(false);
            if (msg != null && msg.length() > 0) {
                mCommitLoading.setLabel(msg);
            }
            if (!isFinishing() && !mCommitLoading.isShowing()) {
                mCommitLoading.show();
            }
        } else if (!mCommitLoading.isShowing() && hasWindowFocus()) {
            if (!isFinishing()) {
                mCommitLoading.show();
            }
        }
    }

    /**
     * 隐藏提交指示器
     * */
    @Override
    public void baseHiddenCommitLoading() {
        if (mCommitLoading != null) {
            try {
                if (mCommitLoading.isShowing() && !isFinishing()) {
                    mCommitLoading.dismiss();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        mCommitLoading = null;
    }

    /**
     * 刷新默认页面状态
     * */
    @Override
    public FCPageStateView baseRefreshPageState(int viewState) {
        return baseRefreshPageState(viewState,-1,null);
    }

    @Override
    public FCPageStateView baseRefreshPageState(int viewState, String msg) {
        return baseRefreshPageState(viewState,-1,msg);
    }

    @Override
    public FCPageStateView baseRefreshPageState(int viewState, int img, String msg) {
        if (viewState == FCPageViewState.PAGE_STATE_NORMAL) {
            if (mStateView != null) {
                mStateView.setViewState(viewState,img,msg);
                mStateView = null;
                return null;
            } else {
                return null;
            }
        }
        if (mStateView == null && mContainerView != null) {
            mStateView = new FCPageStateView(this);
            mStateView.setFCPageStateClickListener(this);
            mContainerView.addView(mStateView);
        }
        if (mStateView != null) {
            mStateView.setViewState(viewState,img,msg);
            mStateView.bringToFront();
        }
        return mStateView;
    }

    /**
     * 刷新默认页面相对顶部偏移
     * */
    @Override
    public FCPageStateView baseRefreshPageStateTopOffset(int topOffset) {
        if (mStateView != null) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)mStateView.getLayoutParams();
            layoutParams.topMargin = topOffset;
            mStateView.setLayoutParams(layoutParams);
        }
        return mStateView;
    }

    @Override
    public FCPageStateView baseRefreshPageStateBottomOffset(int bottomOffset) {
        if (mStateView != null) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)mStateView.getLayoutParams();
            layoutParams.bottomMargin = bottomOffset;
            mStateView.setLayoutParams(layoutParams);
        }
        return mStateView;
    }

    /**
     * 点击失败页面（重新刷新使用）
     * */
    @Override
    public void onClickPageStateErrorView() {

    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      统一回调（目前只处理失败）
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    public void baseShowError() {
        //...
    }

    @Override
    public void baseShowError(String identifer) {

    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      下拉刷新相关
    //
    /////////////////////////////////////////////////////////////////////////////////
    /**
     * 获取下拉刷新控件
     * */
    public SwipeRefreshLayout baseRefreshLayout() {
        if (useRefreshLayout()) {
            return mRefreshView;
        } else {
            throw new RuntimeException("没有设置下拉刷新布局: " + getClass());
        }
    }

    /**
     * 隐藏下拉刷新
     * */
    public void baseEndRefresh() {
        if (mRefreshView != null) {
            if(mRefreshView.isRefreshing()){
                mRefreshView.setRefreshing(false);
            }
        }
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      工具方法
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 获取当前activity
     */
    public Activity getActivity(){
        return this;
    }

    /**
     * 设置状态栏颜色
     *
     * @param dark
     */
    public void setAndroidNativeLightStatusBar(boolean dark) {
        View decor = this.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 设置状态栏透明且全屏
     *
     * @param activity
     */
    public static void setFullScreenAndTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                attributes.flags |= flagTranslucentStatus;
                window.setAttributes(attributes);
            }
        }
    }

    protected String getBundleString(@NonNull String name){
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            return bundle.getString(name);
        }else {
            return "";
        }
    }

    protected void startActivitry(@NonNull Class clazz, String[][] val){
        Intent intent = new Intent(this,clazz);
        Bundle bundle = new Bundle();
        if(val!=null){
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    protected void startActivitryForResult(@NonNull Class clazz,String[][] val){
        Intent intent = new Intent(this,clazz);
        Bundle bundle = new Bundle();
        if(val!=null){
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivityForResult(intent,100);
    }

    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }

    public void addFragmentNeedToStack(Fragment fragment){
        try {
            String tag = fragment.getClass().getName();
            getSupportFragmentManager().beginTransaction().add(Window.ID_ANDROID_CONTENT,fragment,tag).addToBackStack(tag).commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showToast(String str){
        //Toast.makeText(mContext,str,Toast.LENGTH_SHORT).show();
        Toast toast = Toast.makeText(mContext,str, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }


    /** 参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent) **/
    public void goTo(Class<?> goToCls, Object... values) {
        goTo(false, goToCls, values);
    }


    // <editor-fold defaultstate="collapsed" desc="参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent)">
    public void goTo(boolean finish, Class<?> goToCls, Object... values) {
        Intent intent = new Intent(this, goToCls);
        int i = 0;
        for (Object value : values) {
            Class<?> cls = value.getClass();
            String key = String.valueOf(i);
            if (cls == String.class) {
                intent.putExtra(key, (String) value);
            } else if (value instanceof Serializable) {
                intent.putExtra(key, (Serializable) value);
            } else if (cls == int[].class) {
                intent.putExtra(key, (int[]) value);
            } else if (cls == long[].class) {
                intent.putExtra(key, (long[]) value);
            } else if (cls == boolean[].class) {
                intent.putExtra(key, (boolean[]) value);
            } else if (cls == float[].class) {
                intent.putExtra(key, (float[]) value);
            } else if (cls == double[].class) {
                intent.putExtra(key, (double[]) value);
            } else if (cls == char[].class) {
                intent.putExtra(key, (char[]) value);
            } else if (cls == String[].class) {
                intent.putExtra(key, (String[]) value);
            } else if (cls == Bundle.class) {
                intent.putExtra(key, (Bundle) value);
            } else {
                throw new RuntimeException("不支持参数类型: " + cls.getSimpleName());
            }
            i++;
        }
        startActivity(intent);
        if (finish) {
            finish();
        }
    }


    public static void VISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
    }

    public static void INVISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.INVISIBLE);
        }
    }

    public static void GONE(View view) {
        if (view != null) {
            view.setVisibility(View.GONE);
        }
    }

    /** 显示Toast信息 **/
    public void T(Object s) {
        ToastUtil.showToast(String.valueOf(s));
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                     防止多次点击
    //
    /////////////////////////////////////////////////////////////////////////////////

    private static final int MIN_DELAY_TIME = 300;  // 两次点击间隔不能少于300ms
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 判断连续点击事件时间差
            if (isFastClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      销毁
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    public void onBackPressed() {
        onNavigationLeftClick();
    }

    @Override
    protected void onDestroy() {
        // 将其子activity从activity采集器中移除
        UtilActivity.removeActivity(this);
        ImmersionBar.with(this).destroy();
        if(mPresenter!=null){
            mPresenter.onDestroy();
            mPresenter = null;
        }
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}
